package com.ah.shanxi_demo.service.impl;

import com.ah.shanxi_demo.common.enums.OrderCommonEnum;
import com.ah.shanxi_demo.entity.SxOrder;
import com.ah.shanxi_demo.entity.SxOrderReceipt;
import com.ah.shanxi_demo.entity.SxRegister;
import com.ah.shanxi_demo.mapper.SxOrderMapper;
import com.ah.shanxi_demo.mapper.SxRegisterMapper;
import com.ah.shanxi_demo.param.input.OrderPO;
import com.ah.shanxi_demo.param.result.*;
import com.ah.shanxi_demo.service.IOrderService;
import com.ah.shanxi_demo.service.IReceiptService;
import com.ah.shanxi_demo.sync.param.result.SyncOrderResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.ah.shanxi_demo.common.PageUtils.queryPageIndex;
import static com.ah.shanxi_demo.common.RandomUtils.getRandom;
import static com.ah.shanxi_demo.common.SXDateUtils.query_now_month_date;
import static com.ah.shanxi_demo.convert.ConvertOrder.convert_order_list;
import static com.ah.shanxi_demo.convert.ConvertOrder.merge_order_show_ro;
import static com.ah.shanxi_demo.sync.client.SyncOrderClient.order_client;

/**
 * @author zt 2020/8/16
 */
@Service
public class OrderService implements IOrderService {
    private static final Logger log = LoggerFactory.getLogger(RegisterService.class);

    @Autowired
    private SxRegisterMapper registerMapper;

    @Autowired
    private SxOrderMapper orderMapper;

    @Autowired
    private IReceiptService receiptService;

    @Override
    public List<SxOrder> listBySelect(OrderPO orderPO) {
        //获取当前注册表信息 节点唯一标识
        SxRegister sxRegister = registerMapper.selectRecent();
        orderPO.setRegisterId(sxRegister.getRegisterId());

        //分页
        orderPO.setPageIndex(queryPageIndex(orderPO.getPageIndex(), orderPO.getPageSize()));

        //模糊搜索
        if (StringUtils.isNotBlank(orderPO.getTitle())) {
            orderPO.setTitle("%" + orderPO.getTitle() + "%");
        }

        //列表查询
        List<SxOrder> sxOrders = orderMapper.listBySelect(orderPO);
        return sxOrders;
    }

    @Override
    public Integer listCountBySelect(OrderPO orderPO) {
        orderPO.setPageIndex(queryPageIndex(orderPO.getPageIndex(), orderPO.getPageSize()));
        Integer listCountBySelect = orderMapper.listCountBySelect(orderPO);
        return listCountBySelect;
    }

    @Override
    public Boolean deleteOrder(Long[] orderIdList) {
        Arrays.stream(orderIdList).forEach(
                orderId -> {
                    orderMapper.deleteOrder(orderId);
                }
        );
        return Boolean.TRUE;
    }

    @Override
    public SxOrder selectById(Long orderId) {
        SxOrder model = orderMapper.selectById(orderId);
        if (model == null) {
            return new SxOrder();
        }
        return model;
    }

    @Override
    @Transactional
    public void syncOrder() {

        //获取当前注册编码
        SxRegister sxRegister = registerMapper.selectRecent();

        //调用部级平台生成工单数据
        List<SyncOrderResult> orderResultList = order_client(sxRegister);

        //转换为表数据结构
        List<SxOrder> sxOrderList = convert_order_list(orderResultList, sxRegister.getRegisterId());

        //插入工单表数据库
        insertOrderList(sxOrderList);

    }

    @Override
    public void syncSimulationOrder() {
        //获取当前注册编码
        SxRegister sxRegister = registerMapper.selectRecent();
        SxOrder sxOrder = orderFakeModel();
        sxOrder.setRegisterId(sxRegister.getRegisterId());

        try{
            orderMapper.insertOrder(sxOrder);
        }catch (Throwable e){
            log.error("OrderService 【syncSimulationOrder】" + e.getMessage());
        }

    }

    private SxOrder orderFakeModel(){
//        INSERT INTO `bigdata-web`.`sx_policy`(`policy_code`, `guid_type`, `guid`, `policy_status`, `log_type`, `policy_type`)
//        VALUES ('110201-20190710-0002', 1, '1', 0, 'alarm', 'ALM-01-3')

//        UPDATE `bigdata-web`.`sx_order` SET `register_id` = 21, `work_code` = '11-20190710-3', `title` = '进行漏洞',
//        `content` = '漏洞', `accdept` = '生成部', `accuser` = '生成人1', `write_user` = '张', `type` = 1,
//        `level` = 4, `scan_type` = 2 WHERE `order_id` = 5
        SxOrder fakeModel=new SxOrder();
        fakeModel.setWorkCode("11-20190710-3");
        fakeModel.setTitle("模拟部级平台接收数据");
        fakeModel.setContent("模拟部级平台接收数据");
        fakeModel.setAccdept("生成部门");
        fakeModel.setAccuser("生成人");
        fakeModel.setWriteUser("ailpha");
        fakeModel.setType(getRandom(4));
        fakeModel.setLevel(getRandom(3));
        fakeModel.setScanType(getRandom(4));
        fakeModel.setOrderStatus(0);
        fakeModel.setDelete(0);
        return fakeModel;
    }


    @Override
    @Transactional
    public Boolean insertOrderList(List<SxOrder> sxOrderList) {

        Boolean falseBoolean = Boolean.FALSE;
        if (CollectionUtils.isEmpty(sxOrderList)) {
            return falseBoolean;
        }
        sxOrderList.stream().forEach(sxOrder -> {

            //不重复 插入
            if (orderMapper.selectByRepeat(sxOrder) == 0) {
                orderMapper.insertOrder(sxOrder);
            }
        });

        return Boolean.TRUE;
    }

    @Override
    public List<OrderTypeRO> selectOrderType() {

        //获取当前注册编码
        SxRegister sxRegister = registerMapper.selectRecent();

        //查询当前注册编码下的 工单类型
        List<OrderTypeRO> orderTypeROS = orderMapper.selectOrderType(sxRegister.getRegisterId());
        return orderTypeROS;
    }

    @Override
    public OrderTrendRO selectOrderTrend() {
        OrderTrendRO orderTrendRO = new OrderTrendRO();
        List<String> stringList = new ArrayList<>();
        List<Integer> integerList = new ArrayList<>();

        //获取当前注册编码
        SxRegister sxRegister = registerMapper.selectRecent();

        List<NowMonthDaysTimes> list = query_now_month_date(sxRegister.getRegisterId());

        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

        list.stream().forEach(nowMonthDaysTimes -> {

            Integer integer = orderMapper.selectOrderTrend(nowMonthDaysTimes);

            stringList.add(nowMonthDaysTimes.getStartTime());
            integerList.add(integer);

        });

        orderTrendRO.setXtime(stringList);
        orderTrendRO.setYnumber(integerList);

        return orderTrendRO;
    }

    @Override
    public OrderGeneralRO general() {
        //获取当前注册表信息 节点唯一标识
        SxRegister sxRegister = registerMapper.selectRecent();

        OrderGeneralRO model = new OrderGeneralRO();
        model.setFinished(orderMapper.generalFinish(sxRegister.getRegisterId()));
        model.setUnfinished(orderMapper.generalUnFinish(sxRegister.getRegisterId()));
        return model;
    }

    @Override
    public Boolean handleOrderStatus(Long orderId, OrderCommonEnum orderCommonEnum) {

        if (orderMapper.handleOrderStatus(orderId, orderCommonEnum.getKeyInt())) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public OrderShowRO orderShow(Long orderId) {

        //获取工单数据
        SxOrder sxOrder = selectById(orderId);

        //获取工单回执表信息
        SxOrderReceipt sxOrderReceipt = receiptService.selectById(orderId);

        //合并工单数据与回执表数据
        return merge_order_show_ro(sxOrder, sxOrderReceipt);
    }

}
